package org.qtk.server;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;

/**
 * 封装响应信息
 * 
 * @author SiriusTK
 * 
 */
public class Response {

	private StringBuilder headInfo, content;
	private BufferedWriter bw;
	private int len = 0;

	public Response() {
		headInfo = new StringBuilder();
		content = new StringBuilder();
	}

	public Response(OutputStream os) {
		this();
		bw = new BufferedWriter(new OutputStreamWriter(os));
	}

	/**
	 * 构建正文
	 * 
	 * @param content
	 */
	public Response print(String info) {
		content.append(info);
		len += info.getBytes().length;
		return this;
	}

	/**
	 * 构建正文+回车
	 * 
	 * @param content
	 */
	public Response println(String info) {
		content.append(info + "\r\n");
		len += (info.getBytes().length + "\r\n".getBytes().length);
		return this;
	}

	/**
	 * 构建响应头
	 * 
	 * @param code
	 */
	private void createHeadInfo(int code) {
		headInfo.append("HTTP/1.1 " + code + " ");
		switch (code) {
		case 200:
			headInfo.append("OK").append("\r\n");
			break;
		case 404:
			headInfo.append("NOT FOUND").append("\r\n");
			break;
		case 500:
			headInfo.append("SERVER ERROR").append("\r\n");
			break;
		}
		headInfo.append("Server:QTK-server Server/0.0.1").append("\r\n")
				.append("Date:").append(new Date()).append("\r\n")
				.append("Content-type:text/html;charset=utf-8").append("\r\n")
				.append("Content-Length:").append(len).append("\r\n")
				.append("\r\n");
	}

	/**
	 * 把响应推送回客户端
	 * 
	 * @param code
	 * @throws IOException
	 */
	public void pushToClient(int code) throws IOException {
		createHeadInfo(code);
		bw.append(headInfo.toString());
		bw.append(content.toString());
		bw.flush();
		bw.close();
		System.out
				.println("================================================== response ==================================================\r\n"
						+ headInfo.toString() + content.toString());
	}

}
